package config

import (
	"log"

	"admin-system/internal/model"
	"admin-system/pkg/hash"
	"gorm.io/gorm"
)

// InitData 初始化基础数据
func InitData() {
	// 检查是否需要初始化数据
	var count int64
	DB.Model(&model.User{}).Count(&count)
	if count > 0 {
		log.Println("数据库已有数据，跳过初始化")
		return
	}

	log.Println("开始初始化基础数据...")

	// 使用事务确保数据一致性
	err := DB.Transaction(func(tx *gorm.DB) error {
		// 1. 创建权限
		permissions := []model.Permission{
			{Name: "用户查看", Code: "user:list", Description: "查看用户列表"},
			{Name: "用户创建", Code: "user:create", Description: "创建新用户"},
			{Name: "用户编辑", Code: "user:update", Description: "编辑用户信息"},
			{Name: "用户删除", Code: "user:delete", Description: "删除用户"},
			{Name: "角色查看", Code: "role:list", Description: "查看角色列表"},
			{Name: "角色创建", Code: "role:create", Description: "创建新角色"},
			{Name: "角色编辑", Code: "role:update", Description: "编辑角色信息"},
			{Name: "角色删除", Code: "role:delete", Description: "删除角色"},
			{Name: "菜单查看", Code: "menu:list", Description: "查看菜单列表"},
			{Name: "菜单创建", Code: "menu:create", Description: "创建新菜单"},
			{Name: "菜单编辑", Code: "menu:update", Description: "编辑菜单信息"},
			{Name: "菜单删除", Code: "menu:delete", Description: "删除菜单"},
			{Name: "权限查看", Code: "permission:list", Description: "查看权限列表"},
			{Name: "权限创建", Code: "permission:create", Description: "创建新权限"},
			{Name: "权限编辑", Code: "permission:update", Description: "编辑权限信息"},
			{Name: "权限删除", Code: "permission:delete", Description: "删除权限"},
		}
		if err := tx.Create(&permissions).Error; err != nil {
			return err
		}

		// 2. 创建菜单
		dashboardMenu := model.Menu{
			Name:      "Dashboard",
			Path:      "/dashboard",
			Component: "Layout",
			Redirect:  "/dashboard/index",
			Meta:      `{"title":"Dashboard", "icon":"dashboard", "affix":true}`,
			Sort:      1,
		}
		if err := tx.Create(&dashboardMenu).Error; err != nil {
			return err
		}

		dashboardIndexMenu := model.Menu{
			ParentID:  &dashboardMenu.ID,
			Name:      "DashboardIndex",
			Path:      "index",
			Component: "dashboard/index",
			Meta:      `{"title":"首页", "icon":"dashboard"}`,
			Sort:      1,
		}
		if err := tx.Create(&dashboardIndexMenu).Error; err != nil {
			return err
		}

		systemMenu := model.Menu{
			Name:      "System",
			Path:      "/system",
			Component: "Layout",
			Redirect:  "/system/user",
			Meta:      `{"title":"系统管理", "icon":"setting"}`,
			Sort:      2,
		}
		if err := tx.Create(&systemMenu).Error; err != nil {
			return err
		}

		userMenu := model.Menu{
			ParentID:  &systemMenu.ID,
			Name:      "User",
			Path:      "user",
			Component: "system/user/index",
			Meta:      `{"title":"用户管理", "icon":"user"}`,
			Sort:      1,
		}
		if err := tx.Create(&userMenu).Error; err != nil {
			return err
		}

		roleMenu := model.Menu{
			ParentID:  &systemMenu.ID,
			Name:      "Role",
			Path:      "role",
			Component: "system/role/index",
			Meta:      `{"title":"角色管理", "icon":"peoples"}`,
			Sort:      2,
		}
		if err := tx.Create(&roleMenu).Error; err != nil {
			return err
		}

		menuMenu := model.Menu{
			ParentID:  &systemMenu.ID,
			Name:      "Menu",
			Path:      "menu",
			Component: "system/menu/index",
			Meta:      `{"title":"菜单管理", "icon":"tree-table"}`,
			Sort:      3,
		}
		if err := tx.Create(&menuMenu).Error; err != nil {
			return err
		}

		permissionMenu := model.Menu{
			ParentID:  &systemMenu.ID,
			Name:      "Permission",
			Path:      "permission",
			Component: "system/permission/index",
			Meta:      `{"title":"权限管理", "icon":"lock"}`,
			Sort:      4,
		}
		if err := tx.Create(&permissionMenu).Error; err != nil {
			return err
		}

		// 3. 创建角色
		adminRole := model.Role{
			Name:        "超级管理员",
			Description: "系统超级管理员，拥有所有权限",
		}
		if err := tx.Create(&adminRole).Error; err != nil {
			return err
		}

		// 4. 为角色分配权限
		for _, perm := range permissions {
			rolePermission := model.RolePermission{
				RoleID:       adminRole.ID,
				PermissionID: perm.ID,
			}
			if err := tx.Create(&rolePermission).Error; err != nil {
				return err
			}
		}

		// 5. 为角色分配菜单
		menus := []model.Menu{dashboardMenu, dashboardIndexMenu, systemMenu, userMenu, roleMenu, menuMenu, permissionMenu}
		for _, menu := range menus {
			roleMenu := model.RoleMenu{
				RoleID: adminRole.ID,
				MenuID: menu.ID,
			}
			if err := tx.Create(&roleMenu).Error; err != nil {
				return err
			}
		}

		// 6. 创建管理员用户
		hashedPassword, err := hash.HashPassword("admin123")
		if err != nil {
			return err
		}

		adminUser := model.User{
			Username: "admin",
			Password: hashedPassword,
			Name:     "系统管理员",
			Email:    "admin@example.com",
		}
		if err := tx.Create(&adminUser).Error; err != nil {
			return err
		}

		// 7. 为用户分配角色
		userRole := model.UserRole{
			UserID: adminUser.ID,
			RoleID: adminRole.ID,
		}
		if err := tx.Create(&userRole).Error; err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		log.Fatalf("初始化数据失败: %v", err)
	}

	log.Println("初始化基础数据完成")
}
